//
//  BaseTableView.swift
//  ShangYouNews
//
//  Created by Leecong on 2017/4/7.
//  Copyright © 2017年 baymax. All rights reserved.
//

import UIKit
import ESPullToRefresh

private let TitleColor = UIColor.black

public enum TableRefreshState {
    case nomarlState            //  正常状态
    case willHeaderRefresh      //  将要刷新头
    case headerRefreshing       //  正在刷新头
    case endHeaderRefresh       //  结束刷新头
    case willFooterRefresh      //  将要刷新底部
    case footerRefreshing       //  正在刷新底部
    case endFooterRefresh       //  结束底部刷新
    case endFooterRefreshNoData //  结束底部刷新--》没有更多数据
}

open class BaseTableView: UITableView {
    
    override open var delegate: UITableViewDelegate? {
        didSet {
            
        }
    }
    
    var pageindex = 1 //页码
    var pagesize  = 20//每页条数
    
    fileprivate var beginTime : TimeInterval = 0
    fileprivate var endTime   : TimeInterval = 0
    // 是否正在刷新
    
    
    var refreshState : TableRefreshState = .nomarlState{
        didSet{
            preState = refreshState
            guard refreshState == .endFooterRefreshNoData else {
                if refreshState == .endFooterRefresh {
                    if endFooterRefreshComleteBlock != nil {
                        endFooterRefreshComleteBlock!()
                    }
                    refreshState = .nomarlState
                }
                
                return
            }
            
            if refreshState == .endFooterRefreshNoData{
                if endFooterRefreshComleteBlock != nil {
                    endFooterRefreshComleteBlock!()
                }
                
            }
        }
    }
    var preState : TableRefreshState = .nomarlState
    
    
    var footerEndRefreshBlock : refreshComBlock?
    
    public typealias refreshComBlock = ()->Void
    
    var endHeaderRefreshComleteBlock : refreshComBlock?
    var endFooterRefreshComleteBlock : refreshComBlock?
    var canFooterRefresh : Bool = true
    
    var footerView : RefreshFooter?

    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)
        self.setFooter(str: "", showIndi: false)
        self.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        
    }
    
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    
    
    override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "contentOffset" {
            let newOffsetY = (change?[.newKey] as! CGPoint).y
            let offsetY = self.contentOffset.y
            let contentSizeHeigh = self.contentSize.height
            guard contentSizeHeigh > 40 && canFooterRefresh else {
                return
            }
            print("++++\((contentSizeHeigh - offsetY)) -> \(self.bounds.height + 40) state- >\(refreshState)")
            if newOffsetY > CGFloat(10.0)  && (self.refreshState == .nomarlState) && (contentSizeHeigh - offsetY) <= self.bounds.size.height  + 40{
                // 刷新状态设置为将要刷新底部
                self.refreshState = .footerRefreshing
//                if preState != .endFooterRefreshNoData {
                    self.setFooter(str: "正在载入", showIndi: true)
//                }
                if self.delegate is UIViewController {
                    (self.delegate as? UIViewController)?.loadMore()
                } else {
                    (self.delegate as? UIView)?.loadMore()
                }
                
            }
        }
    }
    
    deinit {
        self.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    func getFooterView(hasMore:Bool,string: String)->UIView{
        let footer = UIView()
        let footerContainer = UIView()
        footer.addSubview(footerContainer)
        footerContainer.snp.makeConstraints { (make) in
            make.center.equalTo(footer)
        }
        let waitProgress = UIActivityIndicatorView()
        waitProgress.activityIndicatorViewStyle = .gray
        waitProgress.hidesWhenStopped = true
        waitProgress.clipsToBounds = true
        waitProgress.startAnimating()
        let labText = UILabel()
        labText.font = UIFont.systemFont(ofSize: 11)
        labText.textColor = TitleColor
        labText.text = string
        
        footerContainer.addSubview(waitProgress)
        waitProgress.snp.makeConstraints { (make) in
            make.centerY.left.equalTo(footerContainer)
            make.size.equalTo(CGSize(width: (hasMore ? CGFloat(0.0) : CGFloat(0.0)), height: 30))
        }
        footerContainer.addSubview(labText)
        labText.snp.makeConstraints { (make) in
            make.top.bottom.right.equalTo(footerContainer)
            make.left.equalTo(waitProgress.snp.right)
        }
        
        return footer
    }

    
    override open func draw(_ rect: CGRect) {
        super.draw(rect)
        var header: ESRefreshProtocol & ESRefreshAnimatorProtocol
//        var footer: ESRefreshProtocol & ESRefreshAnimatorProtocol
        
        header = RefreshHeaderAnimator(frame: CGRect.zero) as ESRefreshAnimatorProtocol & ESRefreshProtocol
//        footer = RefreshFooterAnimator.init(frame: CGRect.zero)
        
        self.es.addPullToRefresh(animator: header) { [weak self] in
            self?.beginTime = Date().timeIntervalSince1970
            self?.refreshState = .headerRefreshing
            if self?.delegate is UIViewController {
                (self?.delegate as? UIViewController)?.refresh()
            } else {
                (self?.delegate as? UIView)?.refresh()
            }
        }
        var rect = self.bounds
        rect.size.height = 40
        self.footerView = RefreshFooter(frame: rect)
        
        self.refreshIdentifier = String(Date().timeIntervalSince1970)
        self.expiredTimeInterval = 1
    }
    
    func setFooter(str:String, showIndi:Bool) {
        DispatchQueue.main.async {
            guard self.dataSource != nil else{
                return
            }
//            let num = self.dataSource?.tableView(self, numberOfRowsInSection: 0)
//            if num! == 0{
//                self.footerView?.title = ""
//                self.footerView?.showIndicator = false
//            } else {
                self.footerView?.title = str
                self.footerView?.showIndicator = showIndi
//            }
            
            self.tableFooterView = self.footerView
        }
    }
    
    class RefreshFooter: UIView {
        var footerContainer : UIView?
        var waitProgress : UIActivityIndicatorView?
        var labText : UILabel?
        var title : String?{
            didSet{
                labText?.text = title
            }
        }
        var showIndicator : Bool = false{
            didSet{
                waitProgress?.snp.updateConstraints { (make) in
                    make.size.equalTo(CGSize(width: (showIndicator ? CGFloat(30.0) : CGFloat(0.0)), height: 30))
                }
            }
        }
        override init(frame: CGRect) {
            super.init(frame: frame)
            footerContainer = UIView()
            self.addSubview(footerContainer!)
            footerContainer?.snp.makeConstraints { (make) in
                make.center.equalTo(self)
            }
            waitProgress = UIActivityIndicatorView()
            waitProgress?.activityIndicatorViewStyle = .gray
            waitProgress?.clipsToBounds = true
            waitProgress?.startAnimating()
            labText = UILabel()
            labText?.font = UIFont.systemFont(ofSize: 11)
            labText?.textColor = TitleColor
            
            footerContainer?.addSubview(waitProgress!)
            waitProgress?.snp.makeConstraints { (make) in
                make.centerY.left.equalTo(footerContainer!)
                make.size.equalTo(CGSize(width: 30, height: 30))
            }
            footerContainer?.addSubview(labText!)
            labText?.snp.makeConstraints { (make) in
                make.top.bottom.right.equalTo(footerContainer!)
                make.left.equalTo((waitProgress?.snp.right)!)
            }
            
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
}

extension BaseTableView {
    //MARK: - 表格操作操作相关
    /// 删除刷新头部
    public func removeRefreshHeader() {
        self.es.removeRefreshHeader()
    }
    /// 删除刷新底部
    public func removeRefreshFooter() {
//        self.es.removeRefreshFooter()
        self.canFooterRefresh = false
    }
    /// 自动刷新
    public func autoPullToRefresh() {
        self.es.autoPullToRefresh()
    }
    /// 开始刷新动画
    public func startPullToRefresh() {
        self.es.startPullToRefresh()
    }
    /// 停止刷新动画
    @objc public func stopPullToRefresh(completBlock:refreshComBlock? = nil) {
        self.es.resetNoMoreData()
        endTime = Date().timeIntervalSince1970
        if self.endHeaderRefreshComleteBlock == nil {
            self.endHeaderRefreshComleteBlock = completBlock
        }
        
        let time = 0.6
        if endTime - beginTime < time {
            self.perform(#selector(stopPullToRefresh), afterDelay: time - (endTime - beginTime))
        } else {
            self.es.stopPullToRefresh()
            self.refreshState = .nomarlState
            if self.endHeaderRefreshComleteBlock != nil {
                self.endHeaderRefreshComleteBlock!()
            }
            
        }
    }
    /// 停止加载更多动画
    public func stopLoadingMore(_ string: String = "上拉加载更多") {
        self.refreshState = .endFooterRefresh
        self.setFooter(str: string, showIndi: false)
    }
    
    ///
    public func noticeNoMoreData(_ string: String = "已加载全部内容") {
        self.endFooterRefreshComleteBlock = {() in
            self.setFooter(str: string, showIndi: false)
        }
        self.refreshState = .endFooterRefreshNoData
    }
    
    ///
    public func resetNoMoreData() {
        self.es.resetNoMoreData()
    }
}

extension UIView {
    //MARK: - 下拉刷新相关
    public func refresh(){}
    public func loadMore(){}
}

extension UIViewController {
    //MARK: - 下拉刷新相关
    public func refresh(){}
    public func loadMore(){}
}
